<template>
  <div class="users-view page-view">
    <!-- 页面标题和操作按钮 -->
    <div class="header-section">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleCreate" :icon="Plus"> 添加用户 </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名或邮箱..."
        clearable
        class="w-300 mr-16"
        @input="handleSearch"
      >
        <template #prefix>
          <Search />
        </template>
      </el-input>

      <el-select
        v-model="genderFilter"
        placeholder="选择性别"
        clearable
        class="w-120 mr-16"
        @change="handleGenderChange"
      >
        <el-option v-for="option in GenderOptions" :key="option.value" :label="option.label" :value="option.value" />
      </el-select>

      <el-select v-model="roleFilter" placeholder="选择角色" clearable class="w-150" @change="handleRoleChange">
        <el-option v-for="role in userStore.roles" :key="role.id" :label="role.name" :value="role.id" />
      </el-select>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="userStore.users" :loading="userStore.loading" stripe style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column label="邮箱" min-width="200">
          <template #default="{ row }">
            {{ row.profile?.email || row.email || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.profile ? getGenderText(row.profile.gender) : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="地址" min-width="200">
          <template #default="{ row }">
            {{ row.profile?.address || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id" size="small" style="margin-right: 4px">
              {{ role.name }}
            </el-tag>
            <span v-if="!row.roles?.length">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 错误提示 -->
    <el-alert
      v-if="userStore.error"
      :title="userStore.error"
      type="error"
      show-icon
      closable
      @close="userStore.clearError"
      style="margin-top: 16px"
    />

    <!-- 新增用户对话框 -->
    <CreateUserDialog v-model="showCreateDialog" @success="handleCreateSuccess" />

    <!-- 编辑用户对话框 -->
    <EditUserDialog v-model="showEditDialog" :user="selectedUser" @success="handleEditSuccess" />

    <!-- 用户详情对话框 -->
    <UserDetailDialog v-model="showDetailDialog" :user-id="selectedUserId" @edit="handleEditFromDetail" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/user";
import type { User } from "@/types/user";
import { Gender, getGenderText, GenderOptions } from "@/types/gender";
import CreateUserDialog from "./components/CreateUserDialog.vue";
import EditUserDialog from "./components/EditUserDialog.vue";
import UserDetailDialog from "./components/UserDetailDialog.vue";

defineOptions({
  name: "UsersView",
});

// Store
const userStore = useUserStore();

// 本地状态管理
const searchQuery = ref("");
const genderFilter = ref<Gender | undefined>(undefined);
const roleFilter = ref<number | undefined>(undefined);
const showCreateDialog = ref(false);
const showEditDialog = ref(false);
const showDetailDialog = ref(false);
const selectedUser = ref<User | null>(null);
const selectedUserId = ref<number | undefined>(undefined);
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 搜索防抖
let searchTimer: NodeJS.Timeout | null = null;

// 生命周期
onMounted(async () => {
  // 并行加载用户数据和角色数据
  await Promise.all([loadUsers(), userStore.fetchRoles()]);
});

// 加载用户数据
const loadUsers = async () => {
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      search: searchQuery.value || undefined,
      gender: genderFilter.value,
      roleId: roleFilter.value,
    };
    const response = await userStore.fetchUsers(params);
    pagination.value = {
      page: response.page,
      pageSize: response.pageSize,
      total: response.total,
    };
  } catch (error) {
    console.error("Failed to load users:", error);
  }
};

// 搜索处理（防抖）
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  searchTimer = setTimeout(() => {
    pagination.value.page = 1; // 搜索时重置到第一页
    loadUsers();
  }, 500);
};

// 性别筛选处理
const handleGenderChange = () => {
  pagination.value.page = 1; // 筛选时重置到第一页
  loadUsers();
};

// 角色筛选处理
const handleRoleChange = () => {
  pagination.value.page = 1; // 筛选时重置到第一页
  loadUsers();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.page = 1; // 重置到第一页
  loadUsers();
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  loadUsers();
};

// CRUD操作
const handleCreate = () => {
  showCreateDialog.value = true;
};

const handleCreateSuccess = () => {
  showCreateDialog.value = false;
  // 创建成功后重新加载用户列表
  loadUsers();
};

const handleView = (user: User) => {
  selectedUserId.value = user.id;
  showDetailDialog.value = true;
};

const handleEdit = (user: User) => {
  selectedUser.value = user;
  showEditDialog.value = true;
};

const handleEditFromDetail = (user: User) => {
  // 从详情对话框跳转到编辑对话框
  selectedUser.value = user;
  showEditDialog.value = true;
};

const handleEditSuccess = () => {
  showEditDialog.value = false;
  selectedUser.value = null;
  // 编辑成功后重新加载用户列表
  loadUsers();
};

const handleDelete = async (user: User) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复。`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await userStore.deleteUser(user.id);
    ElMessage.success("删除成功");
    // 删除后重新加载当前页数据
    loadUsers();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};
</script>

<style lang="scss" scoped>
.users-view {
  padding: 24px;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
      color: #303133;
      font-weight: 600;
    }
  }

  .search-section {
    margin-bottom: 16px;
  }

  .table-card {
    .pagination-section {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }
}
</style>
